package com.dding.cms.base.web.util;

import static com.dding.cms.base.web.ActionConstants.BASECONFIG;
import static com.dding.cms.base.web.ActionConstants.MAPPING_PROPERTIES;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.dding.core.log.ILogger;
import org.dding.core.log.LoggerFactory;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;

import com.dding.cms.base.entity.MarkConfig;
import com.dding.cms.base.web.bo.MarkConfigBO;

public class Configuration {

	private static ILogger logger = LoggerFactory
			.getLogger(Configuration.class);

	static Map<Integer, String> mapping = new HashMap<Integer, String>();
	static Properties properties = new Properties();
	static MarkConfigBO config;

	public static Map<Integer, String> getDataTypeMapping() {
		return mapping;
	}

	public static Properties getBaseConfig() {
		return properties;
	}

	public static MarkConfigBO getMarConfig() {
		return config;
	}

	static {
		InputStream stream = Configuration.class.getClassLoader()
				.getResourceAsStream("META-INF/" + MAPPING_PROPERTIES);
		if (stream != null) {
			Properties properties = new Properties();
			try {
				properties.load(stream);
				for (Object key : properties.keySet()) {
					mapping.put(Integer.valueOf((String) key),
							(String) properties.get(key));
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			} finally {
				try {
					stream.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}

		try {
			stream = Configuration.class.getClassLoader().getResourceAsStream(
					"META-INF/" + BASECONFIG);
			properties.load(stream);
		} catch (IOException e) {
			logger.error(e, "load file " + BASECONFIG + " failure.");
			throw new RuntimeException(e);
		}
		@SuppressWarnings("unchecked")
		LazyList<Model> models = MarkConfig.findAll();
		if (models.size() != 1) {
			throw new RuntimeException("can't know config.");
		}
		config = (MarkConfigBO) Utils
				.buildBO(models.get(0), MarkConfigBO.class);
	}
}
